import Icon from '@/components/icon'
import { useInitialState } from '@/hooks'
import { getUserChannelAction } from '@/store/actions/home'
import { Popup, Tabs } from 'antd-mobile'
import styles from './index.module.scss'
import Channels from './components/Channels'
import { useState } from 'react'
import { useDispatch } from 'react-redux'
import { setActive } from '@/store/modules/home'
import ArticleList from './components/ArticleList'
import { useNavigate } from 'react-router-dom'

const Home = () => {
  const nav = useNavigate()
  const dispatch = useDispatch()
  // 1. 获取用户频道数据 || 当前点击频道ID
  const { userChannelList, active } = useInitialState(
    getUserChannelAction,
    'home'
  )
  // 2. 控制频道管理弹层显隐
  const [showChannel, setShowChannel] = useState(false)
  // 3. 我的频道高亮联动
  const taggleActive = (id: string) => {
    dispatch(setActive(parseInt(id)))
  }
  return (
    <div className={styles.root}>
      {/* 1. 频道 Tabs 列表 */}
      {/* 延迟渲染 Tabs，解决 tab 高亮位置错误 */}
      {userChannelList.length > 0 && (
        <Tabs
          activeKey={active + ''}
          onChange={taggleActive}
          className="tabs"
          activeLineMode="fixed">
          {userChannelList.map((item) => (
            <Tabs.Tab title={item.name} key={item.id}>
              {/* 在每个 Tabs.Tab 中渲染文章列表组件 */}
              <ArticleList channelID={item.id} />
            </Tabs.Tab>
          ))}
        </Tabs>
      )}

      {/* 右上角图标 */}
      <div className="tabs-opration">
        {/* 搜索 */}
        <Icon onClick={() => nav('/search')} type="iconbtn_search" />
        {/* 管理频道 */}
        <Icon
          onClick={() => {
            setShowChannel(true)
          }}
          type="iconbtn_channel"
        />
      </div>

      {/* 频道管理弹层 */}
      <Popup className="channel-popup" visible={showChannel} position="right">
        <Channels onClose={setShowChannel} />
      </Popup>
    </div>
  )
}

export default Home
